<template>
	<div class="container">
		<!-- 侧边栏 -->
		<div class="sidebar">
			<div class="sidebar-main">
				<div class="custom-card custom-input">
					<span>{{ project?.name || '未命名项目' }}</span>
				</div>
				<div class="custom-card custom-info">
					<div 
						class="info-circle"
						:style="{ backgroundColor: currentMethodConfig?.color || '#409EFF' }"
					>
						{{ currentMethodConfig?.icon || '📊' }}
					</div>
					<div class="info-cont">
						<div class="title">
							{{ currentMethodConfig?.title || project?.instance?.title || '深度学习项目' }}
						</div>
						<div class="text">
							{{ currentMethodConfig?.description || project?.instance?.description || '暂无描述信息' }}
						</div>
					</div>
				</div>
				<div class="custom-card custom-labels">
					<div class="card-header">
						<div class="title"  @click="handleLabelCollapse">
							<el-icon>
								<component :is="showLabel?'ArrowDown' : 'ArrowUp'"></component>
							</el-icon>
							<span>标签类别</span>
						</div>
					</div>
					<div class="card-body" v-if="showLabel">
						<div class="card-text">
							若要显示实例的子集，请选择一个或多个标签类别。
							<br>
							<br>
							该项目内未标注的图片：{{ unAnnotatedImageCount }} 张
						</div>
						<div class="cell-box">
							<div 
							v-for="category in categoryStats.categories"
							:key="category.key"
							class="cell">
								<span>{{ category.title }}</span>
								<span>{{ category.annotationCount }}</span>
							</div>
							<div v-if="categoryStats.categories.length === 0" class="cell no-data">
								<span colspan="2">暂无标注类别</span>
							</div>
						</div>
					</div>
				</div>
				<div 
				v-if="labelInfo"
				class="custom-card custom-change">
					<div class="card-header">
						<div class="title" @click="handleCollapse">
							<el-icon>
								<component :is="showCollapse?'ArrowDown' : 'ArrowUp'"></component>
							</el-icon>
							<span>已选择</span>
						</div>
						<div 
						class="close"
						@click="handleClose"
						>
							<el-icon><CircleCloseFilled /></el-icon>
						</div>
					</div>
					<div class="card-body" v-if="showCollapse">
						<div class="card-text">{{ labelInfo?.instanceNumber || 1 }}/{{ annotationInstances.length }}个标签实例</div>
						<div class="custom-item">
							<div class="label">图像</div>
							<div class="text">{{ labelInfo?.image || '未选择' }}</div>
						</div>
						<div class="custom-item">
							<div class="label">标签类别</div>
							<div class="text">{{ labelInfo?.name || '未选择' }}</div>
						</div>
						<div class="custom-item">
							<div class="text">{{ labelInfo?.instances || '无详细信息' }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 主内容区域 -->
		<div class="content">
			<div class="cell-box">
				<el-tooltip 
				v-for="(item,index) in annotationInstances"
				:key="`instance-${index}`"
				placement="bottom">
					<template #content>
						<div class="custom-tip-body">
							<div class="text">标签类别：{{ item.name }}</div>
							<div class="text">标签实例：{{ item.instances }}</div>
							<div class="text">图像：{{ item.image }}</div>
							<div class="text">类型：{{ item.type }}</div>
							<div class="text">实例编号：{{ item.instanceNumber }}</div>
						</div>
					</template>
					<div 
					@click.stop="handleChange(item)"
					@dblclick.stop="handleJumpToAnnotation(item)"
					class="cell"
					:class="{ active: labelInfo && item.id == labelInfo.id }"
					>
						<el-image 
						:src="getImageUrl(item)"
						class="cell-img"
						fit="contain"
						:alt="item.name"
						>
							<template #error>
								<div class="image-slot">
									<el-icon><Picture /></el-icon>
									<div>{{ item.name }}</div>
								</div>
							</template>
						</el-image>
						<!-- 显示类别颜色指示器 -->
						<div class="category-indicator" :style="{ backgroundColor: item.color }"></div>
					</div>
				</el-tooltip>
				<div v-if="annotationInstances.length === 0" class="no-annotations">
					<el-icon :size="48"><Picture /></el-icon>
					<p>该项目暂无标注实例</p>
					<p>请先在图像页面进行标注</p>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue'
	import { useProjectStore } from '@store';
	import { useRouter } from 'vue-router';
	
	const projectStore = useProjectStore();
	const router = useRouter();
	const project = computed(() => projectStore.getProject)
	const showLabel = ref(true)
	const labelInfo = ref(null)
	const showCollapse = ref(true)
	
	// 图像缓存
	const imageDataCache = ref(new Map())
	
	// 异步加载图像数据
	const loadImageData = async (imageId, imagePath) => {
		try {
			if (window.electronAPI?.getLocalImageData) {
				const result = await window.electronAPI.getLocalImageData(imagePath)
				if (result.success) {
					// 使用reactive方式更新缓存，确保Vue能检测到变化
					imageDataCache.value = new Map(imageDataCache.value.set(imageId, result.data))
					console.log('[Inspect] 图片数据加载成功:', imageId)
				} else {
					console.error('[Inspect] 图片数据加载失败:', result.error)
				}
			}
		} catch (error) {
			console.error('[Inspect] 图片数据加载异常:', error)
		}
	}
	
	// 获取图像 URL
	const getImageUrl = (item) => {
		if (!item) return ''
		
		// 如果是base64数据，直接返回
		if (item.path && item.path.startsWith('data:')) {
			return item.path
		}
		
		// 如果是文件路径，从缓存中获取
		const cacheKey = `${item.imageData.id}-${item.annotation.id}`
		const cachedData = imageDataCache.value.get(cacheKey)
		if (cachedData) {
			return cachedData
		}
		
		// 如果缓存中没有，异步加载
		if (item.path) {
			loadImageData(cacheKey, item.path)
		}
		
		// 返回空字符串，等待异步加载完成
		return ''
	}
	
	// 加载本地方法配置
	const instanceList = ref([])
	const currentMethodConfig = computed(() => {
		if (!project.value?.instance?.id || !instanceList.value.length) {
			return null
		}
		return instanceList.value.find(method => method.id === project.value.instance.id)
	})
	
	// 从项目数据中提取所有类别信息
	const categoryStats = computed(() => {
		if (!project.value || !project.value.images) return []
		
		// 收集所有类别
		const categories = new Map()
		let totalAnnotationCount = 0
		
		project.value.images.forEach(image => {
			// 从图片的类别定义中收集
			if (image.categories && Array.isArray(image.categories)) {
				image.categories.forEach(category => {
					if (!categories.has(category.key)) {
						categories.set(category.key, {
							key: category.key,
							title: category.title,
							color: category.color,
							annotationCount: 0
						})
					}
				})
			}
			
			// 统计该图片中每个类别的标注数量
			if (image.annotations && Array.isArray(image.annotations)) {
				image.annotations.forEach(annotation => {
					const category = categories.get(annotation.categoryId)
					if (category) {
						category.annotationCount++
						totalAnnotationCount++
					}
				})
			}
		})
		
		return {
			categories: Array.from(categories.values()),
			totalAnnotationCount
		}
	})
	
	// 计算未标注的图片数量
	const unAnnotatedImageCount = computed(() => {
		if (!project.value || !project.value.images) return 0
		
		return project.value.images.filter(image => 
			!image.annotations || image.annotations.length === 0
		).length
	})
	
	// 提取所有标注实例（用于右侧显示）
	const annotationInstances = computed(() => {
		if (!project.value || !project.value.images) return []
		
		const instances = []
		let instanceCounter = 1
		
		project.value.images.forEach(image => {
			if (!image.annotations || !Array.isArray(image.annotations)) return
			
			// 为每个标注创建实例
			image.annotations.forEach(annotation => {
				// 查找对应的类别信息
				const category = image.categories?.find(cat => cat.key === annotation.categoryId)
				const categoryTitle = category?.title || '未知类别'
				const categoryColor = category?.color || '#999999'
				
				// 计算标注区域信息
				let area = 0
				let dimensions = ''
				
				if (annotation.type === 'rectangle') {
					area = Math.round((annotation.width || 0) * (annotation.height || 0))
					dimensions = `${Math.round(annotation.width || 0)}*${Math.round(annotation.height || 0)}`
				} else if (annotation.type === 'line-polygon' && annotation.points) {
					// 计算多边形面积（简化版）
					let polygonArea = 0
					for (let i = 0; i < annotation.points.length; i++) {
						const j = (i + 1) % annotation.points.length
						polygonArea += annotation.points[i].x * annotation.points[j].y
						polygonArea -= annotation.points[j].x * annotation.points[i].y
					}
					area = Math.round(Math.abs(polygonArea / 2))
					dimensions = `${annotation.points.length} points`
				} else if (annotation.type === 'point') {
					area = 1
					dimensions = '1*1'
				}
				
				// 处理缩略图路径
				let thumbnailPath = image.path // 默认使用原图
				if (annotation.thumbnailData) {
					if (annotation.thumbnailData.startsWith('data:')) {
						// 如果是base64数据，直接使用
						thumbnailPath = annotation.thumbnailData
					} else {
						// 如果是文件路径，需要处理
						thumbnailPath = annotation.thumbnailData
					}
				}

				instances.push({
					id: `${image.id}-${annotation.id}`,
					name: categoryTitle,
					color: categoryColor,
					type: annotation.type || 'rectangle',
					image: image.name,
					imagePath: image.path,
					instances: `${categoryTitle}(${dimensions}) A=${area}px`,
					path: thumbnailPath,
					annotation: annotation,
					imageData: image,
					instanceNumber: instanceCounter++
				})
			})
		})
		
		return instances
	})
	
	const handleChange = (item) => {
		labelInfo.value = item
		console.log('[Inspect] 选中标注实例:', item)
	}
	
	const handleLabelCollapse = () => {
		showLabel.value = !showLabel.value
	}
	
	const handleCollapse = () => {
		showCollapse.value = !showCollapse.value
	}
	
	const handleClose = () => {
		labelInfo.value = null
	}

	const handleJumpToAnnotation = (item) => {
		console.log('[Inspect] 双击跳转到标注页面:', item)
		
		// 跳转到图像页面，并传递图片ID和标注ID参数
		router.push({
			name: 'Images',
			query: {
				imageId: item.imageData.id,
				annotationId: item.annotation.id
			}
		})
	}
	

	// 初始化数据
	onMounted(async () => {
		console.log('[Inspect] 检查页面初始化')
		console.log('[Inspect] 当前项目:', project.value)
		
		// 加载本地方法配置
		try {
			if (window.electronAPI?.getLocalMethods) {
				const result = await window.electronAPI.getLocalMethods()
				if (result.success && result.config) {
					instanceList.value = result.config.methods || []
					console.log('[Inspect] 加载方法配置成功:', instanceList.value)
				}
			}
		} catch (error) {
			console.error('[Inspect] 加载方法配置失败:', error)
		}
		
		console.log('[Inspect] 类别统计:', categoryStats.value)
		console.log('[Inspect] 标注实例:', annotationInstances.value)
	})
</script>

<style scoped lang="scss">
.container {
	.sidebar {
		display: flex;
		flex-direction: column;
		padding: 0 0 23px 15px;
		background: transparent;
		border: 0;
		border-radius: 0;
		.sidebar-main{
			display: flex;
			flex-direction: column;
			gap: 10px;
			.custom-card{
				background: linear-gradient( 180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0.4) 100%);
				border-radius: 6px;
				border: 2px solid #FFFFFF;
				padding: 0;
				.card-header{
					position: relative;
					width: 100%;
					cursor: pointer;
					padding: 10px 14px;
					.title{
						display: flex;
						align-items: center;
						gap: 8px;
						cursor: pointer;
						span{
							font-size: 14px;
							color: #333;
						}
						
					}
					.close{
						position: absolute;
						right: 10px;
						top: 50%;
						transform: translateY(-50%);
					}
				}
				.card-body{
					padding: 0 14px 14px;
					.card-text{
						font-size: 12px;
						color: #606266;
					}
				}
			}
			.custom-input{
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 15px;
				span{
					font-size: 14px;
					color: #222;
					font-weight: 600;
				}
			}
			
			.custom-info {
				display: flex;
				align-items: center;
				gap: 10px;
				height: 80px;
				padding: 0 15px;
				
				.info-circle{
					width: 35px;
					height: 35px;
					border-radius: 50%;
					background: #409EFF;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 18px;
					color: white;
					text-shadow: 0 1px 2px rgba(0,0,0,0.2);
					flex-shrink: 0;
				}
				
				.info-cont {
					flex: 1;
					
					.title {
						font-size: 14px;
						color: #333;
						margin-bottom: 4px;
						font-weight: 500;
					}
					
					.text {
						font-size: 12px;
						color: #666;
						line-height: 1.4;
					}
				}
			}
			
			.custom-labels{
				.card-body{
					display: flex;
					flex-direction: column;
					gap: 10px;
					.cell-box{
						border: 1px solid #e5e5e5;
						border-radius: 6px;
						.cell{
							height: 30px;
							
							display: grid;
							grid-template-columns: repeat(2,1fr);
							text-align: center;
							line-height: 30px;
							border-bottom: 1px solid #e5e5e5;
							span{
								font-size: 12px;
								color: #303133;
							}
						}
						.cell:nth-last-of-type(1){
							border: 0;
						}
						
						.no-data {
							color: #909399;
							font-style: italic;
							justify-content: center;
							
							span {
								grid-column: 1 / -1;
								text-align: center;
							}
						}
						
					}
				}
				
			}
			.custom-change{
				.card-body{
					display: flex;
					flex-direction: column;
					gap: 15px;
					.custom-item{
						display: flex;
						flex-direction: column;
						gap: 8px;
						.label{
							font-size: 14px;
							color: #333333;
						}
						.text{
							font-size: 12px;
							color: #606266;
							white-space: wrap;
							word-break: break-all;
						}
					}
				}
			}
		}
	}
	.content{
		display: flex;
		flex-direction: column;
		.cell-box{
			display: flex;
			flex-flow: wrap;
			gap: 20px;
			.cell{
				border-radius: 10px;
				width: 150px;
				min-height: 150px;
				background: #fff;
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				cursor: pointer;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
				transition: all 0.3s ease;
				padding: 8px;
				box-sizing: border-box;
				
				.cell-img{
					width: 134px; /* 150 - 8*2 padding */
					height: 134px;
					background: #f5f7fa;
					border-radius: 8px;
					border: 2px solid transparent;
					box-sizing: border-box;
					object-fit: contain; /* 保持宽高比，完整显示图片 */
					display: flex;
					align-items: center;
					justify-content: center;
				}
				.cell-title{
					font-size: 16px;
					color: #222;
					height: 40px;
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				&:hover {
					box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
					transform: translateY(-2px);
				}
			}
			.active{
				box-shadow: 0 4px 16px rgba(33, 101, 248, 0.2);
				border: 2px solid #2165F8;
			}
			.active::before{
				position: absolute;
				right: 8px;
				top: 8px;
				z-index: 3;
				width: 20px;
				height: 20px;
				content: '✓';
				font-size: 12px;
				font-weight: bold;
				color: #fff;
				background: #2165F8;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2px 4px rgba(0,0,0,0.2);
			}
		}
		
		// 类别指示器
		.category-indicator {
			position: absolute;
			bottom: 8px;
			left: 8px;
			width: 16px;
			height: 16px;
			border-radius: 50%;
			border: 2px solid white;
			box-shadow: 0 1px 3px rgba(0,0,0,0.3);
			z-index: 2;
		}
		
		// 图片加载失败时的占位样式
		.image-slot {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100%;
			background: #f5f7fa;
			color: #909399;
			font-size: 12px;
			
			.el-icon {
				margin-bottom: 8px;
			}
		}
		
		// 无标注时的提示样式
		.no-annotations {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 100%;
			padding: 60px 20px;
			color: #909399;
			text-align: center;
			
			.el-icon {
				margin-bottom: 16px;
				opacity: 0.6;
			}
			
			p {
				margin: 4px 0;
				font-size: 14px;
				line-height: 1.5;
			}
		}
	}
}

// 工具提示样式
.custom-tip-body {
	.text {
		margin: 4px 0;
		font-size: 12px;
		line-height: 1.4;
		color: #fff;
	}
}

</style>